package com.zja.www.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author ja
 * @create 2025/3/31
 * @description 数据库工具类
 */
public class DBUtil {


    private static final String URL = "jdbc:mysql://localhost:3306/hospital";

    private static final String USER = "root";

    private static final String PASSWORD = "3124004489";

    static {
        try {
            // 加载 MySQL 驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("加载数据库驱动失败", e);
        }
    }

    /**
     * 获取数据库连接
     * @return 数据库连接对象
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
    }


    /**
     * 关闭数据库连接
     * @param connection 数据库连接对象
     */
    public static void close(Connection connection) {
        if (connection != null) {
            try {
                // 关闭数据库连接
                connection.close();
                System.out.println("关闭数据库连接成功");
            } catch (SQLException e) {
                System.out.println("关闭数据库连接失败: " + e.getMessage());
            }
        }
    }
}
